from bot_api_v1.app.core.context import request_ctx
from bot_api_v1.app.utils.media_extrat_format import Media_extract_format
from bot_api_v1.app.services.business.media_service import MediaService
from bot_api_v1.app.core.logger import logger
from bot_api_v1.app.core.cache import async_cache_result
from bot_api_v1.app.core.config import settings
# Ensure AuthorInfo is imported if you attempt to construct it, though current logic sets it to None
from bot_api_v1.app.core.schemas import RequestContext, SearchNoteRequest, SearchNoteData, AuthorInfo
from fastapi import HTTPException, Request, status
from typing import Any, Dict, Optional, List
import datetime # Changed from 'import datetime' to 'from datetime import datetime, timedelta' for direct use
from datetime import datetime, timedelta # Added for timedelta
from datetime import datetime, timezone # 确保导入 timezone
from pydantic import HttpUrl # 确保导入 HttpUrl
from bot_api_v1.app.constants.media_info import MediaPlatform

import traceback # 在文件顶部导入
import json
from bot_api_v1.app.core.schemas import KOLPostData
from bot_api_v1.app.constants.media_info import MediaType


class KolPostHelper:
    def __init__(self):
        self.media_service = MediaService()
        self.media_extract_format = Media_extract_format()

    def _unify_post_data(
        self,
        platform_str: str,
        platform_data: List[Dict[str, Any]],
        log_extra: Dict[str, Any]
    ) -> List[KOLPostData]:
        unified_list: List[KOLPostData] = []
        if not platform_data:
            logger.info(f"平台 {platform_str} 未返回任何数据进行统一处理。", extra=log_extra)
            return unified_list

        for item in platform_data:
            try:
                like_c, comment_c, collect_c, share_c = None, None, None, None

                if platform_str == MediaPlatform.DOUYIN:
                    author_info = item.get("author", {})
                    video_info = item.get("video", {})
                    music_info = item.get("music", {})
                    statistics_info = item.get("statistics", {}) # 获取统计信息
                    aweme_type = item.get("aweme_type")
                    
                    media_t = MediaType.UNKNOWN
                    if aweme_type in (0, 4): media_t = MediaType.VIDEO
                    elif aweme_type in (2, 68): media_t = MediaType.IMAGE

                    cover_url_list = video_info.get("origin_cover", {}).get("url_list") or \
                                     video_info.get("cover", {}).get("url_list")
                    
                    img_urls_douyin, vid_url_douyin, duration_douyin = None, None, None

                    if media_t == MediaType.IMAGE and item.get("images"):
                        img_urls_douyin = [
                            img_url for img in item.get("images", [])
                            if img.get("url_list") and (img_url := img.get("url_list")[0])
                        ]
                    elif media_t == MediaType.VIDEO:
                        vid_url_douyin = video_info.get("play_addr", {}).get("url_list", [None])[0]
                        if video_info.get("duration") is not None:
                            duration_douyin = video_info.get("duration") / 1000.0
                        elif music_info.get("duration") is not None:
                            duration_douyin = float(music_info.get("duration"))
                    
                    # 提取抖音互动数据
                    like_c = statistics_info.get("digg_count")
                    comment_c = statistics_info.get("comment_count")
                    collect_c = statistics_info.get("collect_count")
                    share_c = statistics_info.get("share_count")

                    note_data = KOLPostData(
                        note_id=str(item.get("aweme_id")),
                        title=item.get("desc"),
                        platform=platform_str,
                        media_type=media_t,
                        cover_image_url=cover_url_list[0] if cover_url_list and cover_url_list[0] else None,
                        post_url=f"https://www.douyin.com/video/{item.get('aweme_id')}" if item.get('aweme_id') else None,
                        author_id=author_info.get("sec_uid"),
                        author_nickname=author_info.get("nickname"),
                        author_avatar_url=author_info.get("avatar_thumb", {}).get("url_list", [None])[0],
                        create_time=datetime.fromtimestamp(item.get("create_time"), timezone.utc) if item.get("create_time") else None,
                        video_url=vid_url_douyin,
                        video_duration=duration_douyin,
                        image_urls=img_urls_douyin,
                        like_count=like_c,
                        comment_count=comment_c,
                        collect_count=collect_c,
                        share_count=share_c
                    )
                    unified_list.append(note_data)

                elif platform_str == MediaPlatform.XIAOHONGSHU:
                    user_info = item.get("user", {})
                    cover_data = item.get("cover", {})
                    interact_info = item.get("interact_info", {}) # 获取互动信息

                    cover_url = cover_data.get("url_default")
                    if not cover_url and cover_data.get("info_list"):
                        cover_url = cover_data.get("info_list")[0].get("url") if cover_data.get("info_list") else None

                    xhs_type = item.get("type")
                    media_t = MediaType.UNKNOWN
                    if xhs_type == "video": media_t = MediaType.VIDEO
                    elif xhs_type == "normal": media_t = MediaType.IMAGE
                    
                    img_urls_xhs, vid_url_xhs = None, None

                    if media_t == MediaType.IMAGE:
                        if item.get("images_list"):
                             img_urls_xhs = [
                                img.get("url_default") or (img.get("info_list")[0].get("url") if img.get("info_list") else None)
                                for img in item.get("images_list", [])
                                if img.get("url_default") or img.get("info_list")
                            ]
                        elif cover_url:
                            img_urls_xhs = [cover_url]
                    
                    # 提取小红书互动数据
                    # liked_count 在示例中是字符串，需要转换为int
                    liked_count_str = interact_info.get("liked_count")
                    like_c = int(liked_count_str) if liked_count_str and liked_count_str.isdigit() else None
                    
                    # 其他互动数据在小红书列表API摘要中通常不直接提供，设为None或从详情获取
                    comment_c = interact_info.get("comment_count") # 假设可能存在
                    collect_c = interact_info.get("collect_count") # 假设可能存在
                    share_c = interact_info.get("share_count")     # 假设可能存在


                    note_data = KOLPostData(
                        note_id=str(item.get("note_id")),
                        title=item.get("display_title") or item.get("title"),
                        platform=platform_str,
                        media_type=media_t,
                        cover_image_url=cover_url,
                        post_url=f"https://www.xiaohongshu.com/explore/{item.get('note_id')}" if item.get('note_id') else None,
                        author_id=user_info.get("user_id"),
                        author_nickname=user_info.get("nickname") or user_info.get("nick_name"),
                        author_avatar_url=user_info.get("avatar"),
                        create_time=None,
                        video_url=vid_url_xhs,
                        video_duration=None,
                        image_urls=img_urls_xhs,
                        like_count=like_c,
                        comment_count=comment_c, # 如果不存在，会是 None
                        collect_count=collect_c, # 如果不存在，会是 None
                        share_count=share_c
                    )
                    unified_list.append(note_data)
                else:
                    logger.warning(f"统一数据结构：平台 '{platform_str}' 的处理逻辑未实现。跳过作品。", extra=log_extra)
            
            except Exception as unification_error:
                item_id_for_log = item.get("aweme_id") or item.get("note_id") or "UNKNOWN_ID"
                logger.error(
                    f"统一数据结构时处理作品 (ID: {item_id_for_log}, 平台: {platform_str}) 失败: {unification_error}",
                    extra={**log_extra, "item_raw_data": item},
                    exc_info=True
                )
        
        return unified_list
        
    @async_cache_result(expire_seconds=600, prefix="kol_post_helper")
    async def get_kol_post_list_logic(
        self, user_url,req: Request
        ) -> tuple[RequestContext, List[KOLPostData], Dict[str, Any]]:
        trace_key = request_ctx.get_trace_key()
        app_id = request_ctx.get_app_id()
        source = request_ctx.get_source()
        user_id = request_ctx.get_cappa_user_id()
        user_name = request_ctx.get_user_name()
        ip_address = req.client.host if req.client else "unknown_ip"
        platform = self.media_extract_format._identify_platform(user_url)

        request_context = RequestContext(
            trace_id=trace_key, 
            app_id=app_id, 
            user_id=user_id, 
            source=source, 
            user_name=user_name, 
            ip=ip_address,
            timestamp=datetime.now()
        )
        log_extra = {"request_id": trace_key, "user_id": user_id, "app_id": app_id, "platform": platform, "user_url": user_url}
        
        try:
            platform_specific_posts: List[Dict[str, Any]] = await self.media_service.async_get_user_post_note(
                platform, user_url, log_extra
            )
            
            # 调用统一处理方法
            unified_note_list: List[KOLPostData] = self._unify_post_data(
                platform, platform_specific_posts, log_extra
            )
            
            logger.info(f"成功获取并统一了 {len(unified_note_list)} 个来自平台 {platform} 的作品。", extra=log_extra)
            return request_context, unified_note_list, log_extra
            
        except HTTPException: # FastAPI的HTTPException直接重新抛出
            raise
        except Exception as e:
            logger.error(f"get_kol_post_list_logic - 获取用户主页信息失败: {str(e)}", extra=log_extra, exc_info=True)
            # 将其他未知错误包装成HTTPException返回给客户端
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=f"处理用户作品列表时发生内部错误: {str(e)}"
            )
